// stores/userinfo.js 定义一些全局参数变量
import { defineStore } from 'pinia'
import loginApi from '@/api/loginApi.js'
import { addDynamicRoutes } from '@/utils/routerUtils.js'
import { isAuthenticated } from '@/utils/auth.js'

export const useUserStore = defineStore('userinfo', {
  state: () => {
    return {
      userinfo: {}, //用户信息
      permissions: [], //按钮权限
      menuList: [], //左侧导航栏list
    }
  },
  getters: {
    userName: (state) => state.userinfo.username || '用户名',
  },
  actions: {
    //获取用户信息
    async getUserinfo() {
      try {
        const res = await loginApi.userInfo({
          t: +new Date(),
        })
        if (res.code === 0) {
          this.userinfo = res.user || {}
          return this.userinfo
        }
        throw new Error(res.msg || '获取用户信息失败！')
      } catch (error) {
        console.error(error.message || '获取用户信息失败！')
        throw error
      }
    },

    //获取菜单栏
    async getSysMenu() {
      try {
        const res = await loginApi.sysMenu({
          t: +new Date(),
          languageType: 'zh',
          key: '',
        })

        const { code, permissions, menuList } = res
        if (code === 0) {
          this.permissions = permissions || []
          this.menuList = menuList || []
          //动态添加路由
          return addDynamicRoutes(menuList || [])
        }
        throw new Error(res.msg || '获取用户权限信息失败！')
      } catch (error) {
        console.error(error.message || '获取用户权限信息失败！')
        throw error
      }
    },
    // 初始化用户数据
    async initUserData() {
      //先检查token是否存在
      if (!isAuthenticated()) {
        return false
      }
      try {
        await this.getUserinfo()
        await this.getSysMenu()
        return true
      } catch (error) {
        console.error('初始化用户数据失败:', error)
        this.loginOut() // 清理无效状态
        return false
      }
    },
    //退出登录 清空缓存的数据
    loginOut() {
      localStorage.removeItem('userinfo-storage')
      sessionStorage.clear()
      this.$reset()
    },
  },
  persist: {
    key: 'userinfo-storage',
    storage: localStorage,
    paths: ['userinfo', 'permissions', 'menuList'], // 明确指定要持久化的字段
  },
})
